<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="./css/bootstrap.min.css" />
    <style>
      .form-select {
        width: 103px;
        display: inline-block;
      }

      .col-form-label {
        text-align: right;
      }

      .figure-img {
        width: 100px;
        height: 100px;
      }

      #upload {
        display: none;
      }

      .figure-caption {
        cursor: pointer;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <h1 class="p-5">个人设置</h1>
      <form class="col-6">
        <div class="row mb-3">
          <label class="col-form-label col-3">用户名：</label>
          <div class="col-7">
            <input id="username" disabled class="form-control col-9" type="text" />
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-form-label col-3">籍贯：</label>
          <div class="col-9">
            <select class="form-select col-4" name="province">
              <option value="">--省--</option>
            </select>
            <select class="form-select col-4" name="city">
              <option value="">--市--</option>
            </select>
            <select class="form-select col-4" name="county">
              <option value="">--县--</option>
            </select>
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-form-label col-3">头像：</label>
          <div class="col-9">
            <figure class="figure">
              <input type="file" id="upload" />
              <img src="./imgs/default.jpg" class="figure-img img-fluid rounded" alt="..." />
              <figcaption class="figure-caption">修改头像</figcaption>
            </figure>
          </div>
        </div>
        <div class="row mb-3">
          <label class="col-3"></label>
          <div class="col-9">
            <button class="btn btn-primary">保存</button>
          </div>
        </div>
      </form>
    </div>

    <script src="./lib/bootstrap.min.js"></script>
    <script src="./lib/axios.js"></script>
    <script src="./lib/form-value.js"></script>
    <script src="./lib/register.js"></script>
    <script>
      // 尝试发送一个请求，获取用户信息
  (async function () {
  const { data: res } = await axios.get('/user/info')
  // console.log(res)
  // 设置用户名
  document.querySelector('#username').value = res.data.username
  if (res.data.avatar) {
        document.querySelector('img').src = res.data.avatar
      }
      // 判断，如果用户设置过 省、市、县，让对应的省市县选中
      if (res.data.province && res.data.city && res.data.county) {
        // 先获取市和县，渲染到下拉框的位置
        let p1 = axios.get('/api/city', { params: { pname: res.data.province } })
        let p2 = axios.get('/api/county', { params: { pname: res.data.province, cname: res.data.city } })
        // const result = await Promise.all([p1, p2])
        // // console.log(result)
        // const [{ data: shi }, { data: xian }] = result
        const [{ data: shi }, { data: xian }] = await Promise.all([p1, p2])
        // console.log(xian)
        let arr = [`<option value="">--市--</option>`]
        shi.forEach(item => arr.push(`<option value="${item}">${item}</option>`))
        // console.log(arr.join(''))
        city.innerHTML = arr.join('')

        let arr2 = [`<option value="">--县--</option>`]
        xian.forEach(item => arr2.push(`<option value="${item}">${item}</option>`))
        // console.log(arr2.join(''))
        county.innerHTML = arr2.join('')
        // 让省、市、县选中
        province.value = res.data.province
        city.value = res.data.city
        county.value = res.data.county
      }

})()

             // ------------------------ 修改头像 --------------------------
    // 修改头像：1：点击按钮，能够选择图片
    document.querySelector('figcaption').addEventListener('click', function () {
      document.querySelector('#upload').click()
    })
    // 修改头像：2：文件域改变后，上传头像
    document.querySelector('#upload').addEventListener('change', async function () {
      if (this.files.length > 0) {
        // 说明选择了图片
        let fileObj = this.files[0] // 获取文件对象
        let fd = new FormData() // 创建FormData对象
        fd.append('avatar', fileObj) // 把文件对象，添加到 fd 中
        // ajax提交fd即可实现上传
        const { data: res } = await axios.post('/user/avatar', fd)
        // console.log(res)
        document.querySelector('img').src = res.data
      }
    })
      //  省市县
      // 获取
      let province = document.querySelector('[name=province]')
      let city = document.querySelector('[name=city]')
       let county = document.querySelector('[name=county]');
      //  省
      (async function () {
      const { data: res } = await axios.get('/api/province')
      let arr = ['<option value="">--省--</option>']
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`))
      province.innerHTML = arr.join('')
    })()
      // shi
      province.addEventListener('change', async function () {
      county.innerHTML = `<option value="">--县--</option>`
      if (this.value === '') {
        city.innerHTML = `<option value="">--市--</option>`
        return
      }
      const { data: res } = await axios.get('/api/city', { params: { pname: this.value } })
      let arr = [`<option value="">--市--</option>`]
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`))
      city.innerHTML = arr.join('')
    })
    // 切换市的时候，获取对应的县
    city.addEventListener('change', async function () {
      if (this.value === '') {
        county.innerHTML = `<option value="">--县--</option>`
        return
      }
      const { data: res } = await axios.get('/api/county', {
        params: {
          pname: province.value,
          cname: city.value
        }
      })
      let arr = [`<option value="">--县--</option>`]
      res.forEach(item => arr.push(`<option value="${item}">${item}</option>`))
      county.innerHTML = arr.join('')
    })
    // 点击保存
    document.querySelector('button').addEventListener('click',async function(e){
  e.preventDefault()
  let data = val(document.querySelector('form'))
  const{data:res}=await axios.post('/user/info',data)
  if(res.status === 0){
    alert(res.message)
  }
    })
    </script>
  </body>
</html>
